﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace WebSilverlight.Helpers
{
    public class BlobPictureConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                try
                {
                    byte[] blob = (byte[])value;
                    var bmp = PictureHelper.WriteableBitmapFromByteArray(blob);
                    return bmp;
                }
                catch (Exception)
                {
                    //throw new Exception("The Data is not a Valid Picture.");                    
                }
            }

            return new System.Windows.Media.Imaging.BitmapImage(new Uri("/WebSilverlight;component/Resources/editblob.png", UriKind.Relative));   
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                try
                {
                    var bmpSource = (System.Windows.Media.Imaging.BitmapSource)value;
                    var bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmpSource);
                    
                    byte[] blob = PictureHelper.ToByteArray(bmp);
                    return blob;
                }
                catch (Exception)
                {
                    //throw new Exception("The Data is not a Valid Picture.");                    
                }
            }
           
            return string.Empty;
        }
    }
}